﻿using ProjectFootball.MVC.Foundation;
using ProjectFootball.MVC.Foundation.ResourceLibrary;
using ProjectFootball.MVC.Models.EntityFramework.Entities;
using ProjectFootball.MVC.Models.RepositoryProviders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace ProjectFootball.MVC.Areas.MatchArea.Controllers
{
    public class SearchController : BaseController
    {
        #region Constructor
        public SearchController(IRepositoryProvider provider)
            :base(provider)
        {
        }
        #endregion

        #region /MatchArea/Search
        public ActionResult Index(string id1, string id2)
        {
            if (id1 == null || id2 == null || id1.Length <= 1 || id2.Length <= 1)
                return View();

            IEnumerable<Guid> teamVersionGuids1 = Provider.TeamVersionRepository.Where(t => t.TeamName.Contains(id1)).AsEnumerable().Where(t => t.CanView(User)).OrderBy(t => t.TeamName).Select(t => t.TeamGuid);
            IEnumerable<Guid> teamVersionsGuids2 = Provider.TeamVersionRepository.Where(t => t.TeamName.Contains(id2)).AsEnumerable().Where(t => t.CanView(User)).OrderBy(t => t.TeamName).Select(t => t.TeamGuid);

            IEnumerable<Match> matches = Provider.MatchRepository
                .Where(m => (teamVersionGuids1.Contains(m.Team1Guid) && teamVersionsGuids2.Contains(m.Team2Guid))
                    || (teamVersionGuids1.Contains(m.Team2Guid) && teamVersionsGuids2.Contains(m.Team1Guid)))
                .AsEnumerable()
                .Where(m => m.CanView(User));

            var matchSearchResultViewModels = matches.Search(User, SearchType.Text);

            return View(matchSearchResultViewModels);
        }
        #endregion

        [OutputCache(Duration = 0)]
        public JsonResult GetTeamsJSON(string text)
        {
            return Json(Provider.TeamVersionRepository.GetAutoCompleteList(User, text), JsonRequestBehavior.AllowGet);
        }
    }
}
